package com.mcp.client.transport;

import com.mcp.client.transport.McpTransport;
import com.mcp.server.model.McpResponse;
import com.mcp.util.JsonUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

/**
 * Streamable HTTP传输实现
 * 通过HTTP POST发送请求，支持流式响应处理
 */
public class StreamableHttpTransport implements McpTransport {
    private static final String API_URL = "http://localhost:8081/api/mcp";
    
    @Override
    public String send(String request) throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("X-Streamable", "true"); // 标记支持流式响应
        connection.setDoOutput(true);
        
        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = request.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return response.toString();
            }
        } else {
            throw new IOException("HTTP请求失败，响应码: " + responseCode);
        }
    }
    
    /**
     * 流式处理响应
     */
    public void sendWithStreaming(String request, Consumer<McpResponse> responseHandler) throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setRequestProperty("Accept", "text/event-stream"); // 请求流式响应
        connection.setRequestProperty("X-Streamable", "true");
        connection.setDoOutput(true);
        
        // 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = request.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                
                String line;
                StringBuilder responseData = new StringBuilder();
                
                while ((line = br.readLine()) != null) {
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        responseData.append(data);
                        
                        // 尝试解析JSON响应
                        try {
                            McpResponse response = JsonUtils.fromJson(responseData.toString(), McpResponse.class);
                            if (response != null) {
                                responseHandler.accept(response);
                                responseData.setLength(0); // 重置缓冲区
                            }
                        } catch (Exception e) {
                            // 可能是部分响应，继续读取
                        }
                    }
                }
                
                // 处理最后一个响应
                if (responseData.length() > 0) {
                    try {
                        McpResponse response = JsonUtils.fromJson(responseData.toString(), McpResponse.class);
                        if (response != null) {
                            responseHandler.accept(response);
                        }
                    } catch (Exception e) {
                        // 忽略解析错误
                    }
                }
            }
        } else {
            throw new IOException("HTTP请求失败，响应码: " + responseCode);
        }
    }
    
    @Override
    public void close() throws Exception {
        // 无资源需要关闭
    }
}